#include <gr_graph_fun.h>

#include "watch.h"
#include "perror_exit.h"

w3lWatch *
find_watch(LNode_type *watches, int id)
{
	LNode_type *ptr;

	assert(watches != NULL);
		
	for(ptr=watches->back;ptr!=watches;ptr=ptr->back)
		if(((w3lWatch *)(ptr->info))->id == id)
			return ((w3lWatch *)(ptr->info));

	return NULL;
}

int
max_watch_id(LNode_type *watches)
{
	LNode_type *ptr;
	int maxid = 0;
	
	assert(watches != NULL);
	
	for(ptr=watches->back;ptr!=watches;ptr=ptr->back)
		if(((w3lWatch *)(ptr->info))->id > maxid)
			maxid = ((w3lWatch *)(ptr->info))->id;
	
	return maxid;
}

void
add_watch(LNode_type *watches, w3lWatch *watch)
{
	Insert_linked_list(watches,create_new_node_llist((void *)watch));
}

short
del_watch(LNode_type *watches, int id)
{
	LNode_type *ptr;
	
	assert(watches != NULL);
	
	for(ptr=watches->back;ptr!=watches;ptr=ptr->back) {
		if(((w3lWatch *)(ptr->info))->id == id) {
			ptr->back->next = ptr->next;
			ptr->next->back = ptr->back;
			free(ptr->info);
			return 1;
		}
	}
	return 0;
}

w3lWatch *
create_watch(char *description, short active, int id, void *arg, short arg_is_string, void(*check)(struct _w3lWatch *watch, log_line *line))
{
	w3lWatch *w = NULL;

	assert(check!=NULL);

	if(!(w = (w3lWatch *)malloc(sizeof(w3lWatch))))
		perror_exit("malloc() (%s:%d)",__FILE__,__LINE__);

	w->description = strdup(description);
	w->active = active;
	w->id = id;
	w->arg_is_string = arg_is_string;
	w->arg = arg;
	w->check = check;
	w->status = NULL;

	return w;
}

char *
check_watch(w3lWatch *watch)
{
	char *stat;

	if(watch->status == NULL)
		return NULL;

	stat = strdup(watch->status);
	free(watch->status);
	watch->status = NULL;

	return stat;
}


WATCH_FUNC(w_url)
{
	if(strstr(line->curl,(char *)(watch->arg)) && !(watch->status)) {
		watch->status = cat("The web user at %s accessed %s on %s",
				line->cursite,line->curl,line->curdate);
	}
}

WATCH_FUNC(w_domain)
{
	if(strstr(line->cursite,(char *)(watch->arg)) && !(watch->status))
		watch->status = cat("The web user at %s accessed %s on %s",
				line->cursite,line->curl,line->curdate);
}

